/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tcpserver;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import util.ByteStream;

/**
 *
 * @author Hnmtuan
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        String clientSentence = "";
        String capitalizedSentence = "";

        Integer portNums = 1610;

        ServerSocket welcomeSocket = null;
        File f = null;
        try {
            f = new File("send.txt");
            if (f.exists()){System.out.println("File found !");}else{System.out.println("File not found !");}
            
            // Create Handsaked connection
            welcomeSocket = new ServerSocket(portNums);
            System.out.println("Waiting client ..... !");
            // Listen client connection
            while (true) {
                Socket connectSocket = welcomeSocket.accept();
                
                if (connectSocket == null ){System.exit(1);}

                new Thread(new Process(connectSocket, f)).start();

               System.out.println("Client connect .... ! \n");
            
            }

        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
   
}
class Process implements Runnable {

        Socket s;
        DataOutputStream output; // Out to send data to client
        DataInputStream input; // In to received data to client
        FileInputStream fis;
        OutputStream op;
        
        File f;

        public Process(Socket cliSock, File fileOutput) {
            s = cliSock;
            f = fileOutput;
        }

        public void run() {
            try {
//                output = new DataOutputStream(s.getOutputStream());
//                input = new DataInputStream(s.getInputStream());
                op = s.getOutputStream();
                
                byte[] buf=new byte[512];
                int len;

                int files = 1;
                System.out.println("Begin nums file " + files);
                ByteStream.toStream(op, files);
                System.out.println("End nums file " + files);

                System.out.println("Begin Send file " + f.getName());
                ByteStream.toStream(op, f.getName());
                ByteStream.toStream(op, f);
                System.out.println("End Send file " + f.getName());
                
                s.close();
            } catch (Exception e) {
                System.out.print(e.getMessage());
            }
        }
    }